﻿using Sidvall.Data;
using Sidvall.WorkItemManager.Data;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Model.DataPortalManagers
{
    public partial class WorkItemSensorManager<TEntity, TList>
    {
        #region Public Members

        #region GetSensorsAsync

        public async Task<SensorValueCollection> GetSensorsAsync(int? serverConnectionId, long workItemId)
        {
            var item = new CommandCriteria()
            {
                CriteriaId = ParameterManager.WorkItemSensorGetParameterName,
                Parameters = new ParameterCollection(),
            };
            if (serverConnectionId != null)
                item.Parameters.Add(nameof(Sidvall.WorkItemManager.Data.Fields.WorkItemField.ServerConnectionId), serverConnectionId.Value);
            item.Parameters.Add(nameof(Sidvall.WorkItemManager.Data.Fields.WorkItemField.WorkItemId), workItemId);
            item = await Sidvall.WorkItemManager.SystemContext.Current.DataPortal.WorkItemSensorManager.ExecuteAsync(item).ConfigureAwait(false);
            return item.Parameters.ValueToObject<SensorValueCollection>(ParameterManager.SensorsParameterName, null);
        }

        #endregion
        #region LoadSensorsAsync

        public async Task LoadSensorsAsync(Sidvall.WorkItemManager.Workflow.IWorkItemProvider workItemProvider, int? serverConnectionId, long workItemId)
        {
            workItemProvider.SensorValues.Clear();
            var sensors = await GetSensorsAsync(serverConnectionId, workItemId).ConfigureAwait(false);
            if (sensors != null)
            {
                foreach (var sensor in sensors)
                    workItemProvider.SensorValues.Add(sensor);
            }
        }

        #endregion

        #endregion
    }
}